import { CMCClient } from "mpj-cmc/cmc.client";
import { CMCServer } from "mpj-cmc/cmc.server";

export class FrontNotifyServer {
    private cmcSvr: CMCServer;
    private cmcClient: CMCClient;

    constructor(options: FNSOptions) {
        this.cmcClient = new CMCClient(options.cnsHostName, options.cnsPort, options.storeId);
        this.cmcSvr = new CMCServer(options);
    }
    Start() {
        if (this.cmcSvr) {
            this.cmcSvr.Open();
            this.cmcSvr.Listen();
            this.cmcSvr.onReceived = (msg: NoticeBase, sender) => {
                if (msg.type == "RegisHandler") {
                    console.log("客户端[" + sender.ClientId + "]注册：" + msg.content.notifyType);

                    this.RegistMessageHandler(msg.content.notifyType, sender);
                }
                else if (msg.type == "RemoveHandler") {
                    console.log("客户端[" + sender.ClientId + "]注销：" + msg.content.notifyType);

                    this.RemoveMessageHanler(msg.content.notifyType, sender);
                }
                else if (msg.type == "Notify") {
                    console.log("客户端[" + sender.ClientId + "]发送消息：" + msg.content);
                    this.Notify(msg.content, sender);
                }
                else {
                    //when business message received.relay the message to handler.
                    this.RelayMessage(msg, sender);
                }
            }
            this.cmcSvr.onClientDisconnect = sender => {
                for (let i = 0; i < this.msgHandlerList.length; i++) {
                    if (this.msgHandlerList[i].clientId == sender.ClientId) {
                        this.msgHandlerList.splice(i, 1);
                        break;
                    }
                }
            }
        }

        if (this.cmcClient) {
            this.cmcClient.Connect();
            this.cmcClient.onReceive = (msg) => {
                console.log("收到CNS的消息", msg);
                this.RelayMessage(msg);
            }
        }
    };
    Stop() {
        if (this.cmcSvr && this.cmcSvr.IsOpened) {
            this.cmcSvr.Close();
        }
    };
    Notify(msg: NoticeBase, sender) {
        this.RelayMessage(msg, [sender]);
    }

    private RelayMessage(msg: NoticeBase, exclude?: any[]) {
        // console.log("当前消息处理器列表：", this.msgHandlerList);
        try {
            for (let item of this.msgHandlerList) {
                if (exclude) {
                    if (exclude.find(x => x.ClientId == item.clientId)) continue;
                }
                if (item.noticeType == msg.type) {
                    this.cmcSvr.Send(item.clientId, msg);
                }
            }
        } catch (error) {
            console.error("发送消息失败：", error);
        }
    }

    private msgHandlerList: { noticeType: string, clientId: string }[] = [];
    RegistMessageHandler(noticeType: string, sender: { ClientId: string }) {
        let has = false;
        for (let item of this.msgHandlerList) {
            if (item.noticeType == noticeType && item.clientId == sender.ClientId) {
                has = true;
                break;
            }
        }
        if (!has) {
            this.msgHandlerList.push({
                noticeType: noticeType,
                clientId: sender.ClientId
            });
        }
    }

    RemoveMessageHanler(noticeType: string, sender: { ClientId: string }) {
        let item = this.msgHandlerList.findIndex(x => x.noticeType == noticeType && x.clientId == sender.ClientId);
        if (item) {
            this.msgHandlerList.splice(item, 1);
        }
    }
}

interface NoticeBase {
    type: string;
    content: any;
}

interface FNSOptions {
    cnsHostName: string;
    cnsPort: number;
    storeId: string;
    port: number,
    port_https: number
}


